// hive_visual_screen.dart
import 'package:chat_client/models/apply_model.dart';
import 'package:chat_client/models/contact_model.dart';
import 'package:chat_client/models/group_model.dart';
import 'package:chat_client/models/user_model.dart';
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:chat_client/repositories/hive_repository.dart';

class HiveVisualScreen extends StatefulWidget {
  const HiveVisualScreen({super.key});

  @override
  HiveVisualScreenState createState() => HiveVisualScreenState();
}

class HiveVisualScreenState extends State<HiveVisualScreen> {
  final List<String> _boxNames = [
    'self',
    'contact',
    'group',
    'groupMember',
    'apply',
    'conversation'
  ];
  late Box? _currentBox;
  String _currentBoxName = '';
  String _searchQuery = '';
  final Map<String, dynamic> _newEntry = {'key': '', 'value': ''};

  @override
  void initState() {
    super.initState();
    _currentBox = null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:
            Text(_currentBox == null ? 'Hive Boxes' : 'Box: $_currentBoxName'),
        actions: _buildAppBarActions(),
      ),
      body: _currentBox == null ? _buildBoxList() : _buildBoxContents(),
      backgroundColor: Colors.white,
      floatingActionButton: _currentBox != null
          ? FloatingActionButton(
              onPressed: _showAddEntryDialog,
              child: const Icon(Icons.add),
            )
          : null,
    );
  }

  // 构建 Box 列表
  Widget _buildBoxList() {
    return ListView.builder(
      itemCount: _boxNames.length,
      itemBuilder: (context, index) {
        final boxName = _boxNames[index];
        return ListTile(
          title: Text(boxName),
          trailing: const Icon(Icons.arrow_forward),
          onTap: () => _openBox(boxName),
        );
      },
    );
  }

  // 构建 Box 内容
  Widget _buildBoxContents() {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: TextField(
            decoration: const InputDecoration(
              labelText: 'Search...',
              prefixIcon: Icon(Icons.search),
            ),
            onChanged: (value) => setState(() => _searchQuery = value),
          ),
        ),
        Expanded(
          child: ValueListenableBuilder(
            valueListenable: _currentBox!.listenable(),
            builder: (context, Box box, widget) {
              final entries = box.keys
                  .where((key) => key.toString().contains(_searchQuery))
                  .toList();
              return ListView.builder(
                itemCount: entries.length,
                itemBuilder: (context, index) {
                  final key = entries[index];
                  final value = box.get(key);
                  return _buildEntryItem(key, value);
                },
              );
            },
          ),
        ),
      ],
    );
  }

  // 构建单个条目
  Widget _buildEntryItem(dynamic key, dynamic value) {
    return ExpansionTile(
      title: Text('Key: $key'),
      subtitle: Text('Type: ${value.runtimeType}'),
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Value:', style: TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(height: 8),
              _buildValuePreview(value),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  IconButton(
                    icon: const Icon(Icons.edit, color: Colors.blue),
                    onPressed: () => _showEditDialog(key, value),
                  ),
                  IconButton(
                    icon: const Icon(Icons.delete, color: Colors.red),
                    onPressed: () => _deleteEntry(key),
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 构建值预览（支持复杂对象）
  Widget _buildValuePreview(dynamic value) {
    if (value is Map || value is List) {
      return Text(
        value.toString(),
        style: const TextStyle(fontFamily: 'monospace'),
      );
    }
    if (value is User) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('UserID: ${value.userId}'),
          Text('Phone Number: ${value.phoneNumber}'),
          Text('Username: ${value.username}'),
          Text('Nickname: ${value.nickname}'),
          Text('Avatar URL: ${value.avatarUrl}'),
          Text('Gender: ${value.gender == 1 ? 'Male' : 'Female'}'),
          Text('Birthday: ${value.birthday}'),
          Text('Region: ${value.region}'),
          Text('Region Code: ${value.regionCode}'),
          Text('Signature: ${value.signature}'),
          Text('Add Type: ${value.addType == 1 ? 'Allowed' : 'Not Allowed'}'),
        ],
      );
    }
    // For Apply data type
    if (value is Apply) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Is Send: ${value.isSend ? 'Yes' : 'No'}'),
          Text('Opponent ID: ${value.opponentId}'),
          Text('Opponent Nickname: ${value.opponentNikename}'),
          Text('Opponent Avatar URL: ${value.opponentAvatarUrl}'),
          Text('Apply Info: ${value.applyInfo}'),
          Text(
              'Status: ${value.status == 0 ? 'Pending' : value.status == 1 ? 'Friend' : 'Invalid'}'),
          Text('Created At: ${value.createdAt.toString()}'),
        ],
      );
    }

// For Contact data type
    if (value is Contact) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('User ID: ${value.userId}'),
          Text('Nickname: ${value.nickname}'),
          Text('Username: ${value.username}'),
          Text('Avatar URL: ${value.avatarUrl}'),
          Text('Region: ${value.region}'),
          Text('Signature: ${value.signature}'),
          Text('Gender: ${value.gender == 1 ? 'Male' : 'Female'}'),
          Text('Remark: ${value.remark}'),
          Text(
              'Status: ${value.status == 1 ? 'Friend' : value.status == 2 ? 'Deleted' : 'Blocked'}'),
          Text('Created At: ${value.addAt.toString()}'),
        ],
      );
    }

// For Group data type
    if (value is Group) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Group ID: ${value.groupId}'),
          Text('Group Name: ${value.groupName}'),
          Text('Group Avatar URL: ${value.groupAvatar}'),
          Text('Verify Type: ${value.vertifyType}'),
        ],
      );
    }

    return Text(value.toString());
  }

  // 打开 Box
  Future<void> _openBox(String boxName) async {
    final box = await HiveService.instance.openBox(boxName);
    setState(() {
      _currentBox = box;
      _currentBoxName = boxName;
    });
  }

  // 添加条目对话框
  void _showAddEntryDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Add New Entry'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              decoration: const InputDecoration(labelText: 'Key'),
              onChanged: (value) => _newEntry['key'] = value,
            ),
            TextField(
              decoration: const InputDecoration(labelText: 'Value'),
              onChanged: (value) => _newEntry['value'] = value,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              _currentBox?.put(_newEntry['key'], _newEntry['value']);
              Navigator.pop(context);
            },
            child: const Text('Save'),
          ),
        ],
      ),
    );
  }

  // 编辑条目对话框
  void _showEditDialog(dynamic key, dynamic value) {
    final controller = TextEditingController(text: value.toString());
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('Edit Entry: $key'),
        content: TextField(
          controller: controller,
          maxLines: 5,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              _currentBox?.put(key, controller.text);
              Navigator.pop(context);
            },
            child: const Text('Save'),
          ),
        ],
      ),
    );
  }

  // 删除条目
  void _deleteEntry(dynamic key) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Confirm Delete'),
        content: Text('Delete entry with key "$key"?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              _currentBox?.delete(key);
              Navigator.pop(context);
            },
            child: const Text('Delete'),
          ),
        ],
      ),
    );
  }

  // 构建 AppBar 操作按钮
  List<Widget> _buildAppBarActions() {
    if (_currentBox == null) return [];
    return [
      IconButton(
        icon: const Icon(Icons.delete_sweep),
        onPressed: () => _clearCurrentBox(),
        tooltip: 'Clear Box',
      ),
      IconButton(
        icon: const Icon(Icons.close),
        onPressed: () => setState(() => _currentBox = null),
        tooltip: 'Close Box',
      ),
    ];
  }

  // 清空当前 Box
  void _clearCurrentBox() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Confirm Clear'),
        content: Text('Clear all entries in $_currentBoxName?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              _currentBox?.clear();
              Navigator.pop(context);
            },
            child: const Text('Clear'),
          ),
        ],
      ),
    );
  }
}
